/**
 * 
 */
package cn.sdhuijin.healthexam;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;

/**
 * 读取csv文件，生成SQL语句
 * 
 * @author Administrator
 * 
 */
public class ReadFile {
	/**
	 * 读取csv文件，生成SQL语句
	 * 
	 * @param csv
	 * @throws Exception
	 */
	public static String ReadCSVFile(InputStreamReader inputReader)
			throws Exception {
		String crateSql = "";
		try {
			BufferedReader br = new BufferedReader(inputReader);
			String s[];
			ArrayList<String[]> list = new ArrayList<String[]>();
			// 读取第一行
			String firstLine = br.readLine();
			if (firstLine == null || firstLine.equals("")) {
				throw new Exception("csv数据库表文件中表名！");
			}
			s = firstLine.split(",");
			String tableName = "";
			if (s.length > 0) {
				tableName = s[0];
			}
			// 从第二行读取直到最后一行
			String line = "";
			while ((line = br.readLine()) != null) {
				// 分割字符串
				s = line.split(",");
				list.add(s);
			}
			br.close();
			crateSql = "CREATE TABLE IF NOT EXISTS " + tableName + "("
					+ printSql(list).toString() + ")";
		} catch (FileNotFoundException e) {
			// 捕获File对象生成时的异常
			e.printStackTrace();
		} catch (IOException e) {
			// 捕获BufferedReader对象关闭时的异常
			e.printStackTrace();
		}
		return crateSql;
	}

	public static StringBuffer printSql(ArrayList<String[]> list) {
		Iterator<String[]> it1 = list.iterator();
		String[] s;
		StringBuffer sql = new StringBuffer();
		while (it1.hasNext()) {
			s = (String[]) it1.next();
			// 拼接类型
			sql.append(s[0] + " " + s[1]);
			// 拼接长度
			if ((s[2] != null) && !(s[2].equals(""))) {
				sql.append("(" + s[2] + ")");
			}
			// 拼接主键
			if (s[3].equals("Y")) {
				sql.append(" PRIMARY KEY");
			}
			// 拼接是否为空
			if (s[4].equals("N")) {
				sql.append(" NOT NULL");
			}
			if (s.length > 5) {
				sql.append(" DEFAULT '" + s[5] + "'");
			}
			sql.append(",");
		}
		// 截取掉最后一个逗号
		if ((sql.length() > 0) && (',' == sql.charAt(sql.length() - 1)))
			sql = sql.deleteCharAt(sql.length() - 1);
		return sql;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String fileName = "E:" + File.separator + "houyc" + File.separator
				+ "项目" + File.separator + "智能终端项目" + File.separator + "项目文档"
				+ File.separator + "数据库csv文件";
		File f = new File(fileName);
		File[] fileList = null;
		if (f.isDirectory()) {
			fileList = f.listFiles();
			for (int i = 0; i < fileList.length; i++) {
				System.out.println(fileList[i]);
				File csv = fileList[i];
				try {
					InputStreamReader inputReader = new InputStreamReader(
							new FileInputStream(csv), "GBK");
					System.out.println(ReadFile.ReadCSVFile(inputReader));
				} catch (Exception e) {
					System.out.println(e.getMessage() + "创建失败！");
				}
			}
		}
	}

}
